using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Reflection;
using Magiq.Tests;

namespace Magiq.Sql.Tests {
  public class MagiqToSqlTestConfigurator : IMagiqTestConfigurator {
    protected DataContext dataContext;

    static MagiqToSqlTestConfigurator() {
      Current = new MagiqToSqlTestConfigurator();
    }

    private MagiqToSqlTestConfigurator() {}
    public static MagiqToSqlTestConfigurator Current { get; private set; }

    #region IMagiqTestConfigurator Members

    public IQueryable<T> PersistAndGet<T>(IList<T> items) where T : class {
      foreach (var item in items)
        dataContext.GetTable<T>().InsertOnSubmit(item);

      dataContext.SubmitChanges();

      return dataContext.GetTable<T>();
    }

    public void SetUp() {
      Magiq.Clear()
        .Register<MagiqToSql>();

      var mapping = Assembly.GetExecutingAssembly().GetManifestResourceStream("Magiq.Sql.Tests.Mappings.xml");
      var mappingSource = XmlMappingSource.FromStream(mapping);

      dataContext = new DataContext(ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString,
                                    mappingSource);

      if (dataContext.DatabaseExists())
        dataContext.DeleteDatabase();
      dataContext.CreateDatabase();
    }

    public void TearDown() {
      var c = dataContext.Connection;
      if (c.State != ConnectionState.Closed)
        c.Close();
      dataContext.Dispose();
      c.Dispose();
    }

    public IQueryable<T> GetQueryable<T>() where T : class {
      return dataContext.GetTable<T>();
    }

    #endregion

    #region Nested type: MyClass

    public class MyClass {}

    #endregion
  }
}